<template>
    <div class="container-fluid">
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>场馆功能管理</h1>
            </div>
        </div>
        <el-row>
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="功能">
                    <el-select v-model="searchForm.type" @change="getList(true)" placeholder="请选择">
                        <el-option :value="0" label="前台"></el-option>
                        <el-option :value="1" label="后台"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item>
                    <el-button type="primary" @click="getList">查询</el-button>
                </el-form-item> -->
            </el-form>
        </el-row>
        <div class="view">
            <el-tree v-loading="loading" class="view-left" :data="viewTreeList" node-key="viewId" :default-expanded-keys="['']" :props="defaultProps" @node-click="handleNodeClick">
                <span class="custom-tree-node" slot-scope="{node,data}">
                    <span>{{node.label}}</span>
                    <i class="fa fa-plus" @click="add(data,node)"></i>
                </span>
            </el-tree>
            <div class="view-right">
                <el-table :data="tableData" border style="width: 100%" :header-cell-class-name="headerbg">
                    <el-table-column prop="sort" label="序号" align="center" width="50"></el-table-column>
                    <el-table-column prop="viewName" label="功能名称"></el-table-column>
                    <el-table-column prop="url" label="链接"></el-table-column>
                    <el-table-column prop="icon" label="图标"></el-table-column>
                    <el-table-column prop="viewDesc" label="信息描述"></el-table-column>
                    <el-table-column prop="type" label="类型">
                        <span slot-scope="scope">{{scope.row.type?'后台功能':'前台功能'}}</span>
                    </el-table-column>
                    <el-table-column prop="valid" width="80" label="是否有效">
                        <span slot-scope="scope">{{scope.row.valid?'是':'否'}}</span>
                    </el-table-column>
                    <!-- <el-table-column prop="creationTime" label="创建时间"></el-table-column> -->
                    <!-- <el-table-column prop="lastModifiedTime" label="修改时间"></el-table-column> -->
                    <el-table-column label="操作" align="center" min-width="70">
                        <template slot-scope="scope">
                            <el-tooltip content="编辑" placement="top">
                                <i class="fa fa-edit el-text-blue" @click="edit(scope.row.viewId)"></i>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <i class="fa fa-trash el-text-danger" @click="del(scope.row.viewId)"></i>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>    
        <!--添加/编辑-->
        <el-dialog :title="(form.viewId?'编辑':'添加')+'场馆功能'" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="form" :rules="rules" label-width="25%">
                <el-form-item label="父级：" v-if="!form.viewId">
                    {{selectView.viewName||'无'}}
                </el-form-item>
                <el-form-item label="功能名称：" prop="viewName">
                    <el-input v-model.trim="form.viewName" placeholder="请输入功能名称" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="链接：" prop="url">
                    <el-input v-model.trim="form.url" placeholder="请输入链接" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="序号：" prop="sort">
                    <el-input type="number" v-model.trim.number="form.sort" placeholder="请输入序号" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="图标：" prop="icon">
                    <el-input v-model.trim="form.icon" placeholder="请输入图标" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="描述信息：" prop="viewDesc">
                    <el-input type="textarea" :rows="2" v-model.trim="form.viewDesc" placeholder="请输入描述信息" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="是否有效：" prop="valid">
                    <el-radio-group v-model="form.valid">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="类型：" prop="type">
                    <el-radio-group v-model="form.type" disabled>
                        <el-radio :label="0">前台功能</el-radio>
                        <el-radio :label="1">后台功能</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="有无子功能表：" prop="is_leaf">
                    <el-radio-group v-model="form.is_leaf">
                        <el-radio :label="true">有</el-radio>
                        <el-radio :label="false">无</el-radio>
                    </el-radio-group>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="medium">确 定</el-button>
                <el-button @click="dialogFormVisible = false" size="medium">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data(){
            return{
                headerbg:'headerbg',//表格头部背景色
                dialogFormVisible:false,
                tableData:[],
                rules:{
                    viewName:[
                        { required: true, message: '请输入功能名称', trigger: 'blur' },
                    ],
                    valid:[
                        { required: true, message: '请选择是否有效', trigger: 'change' },
                    ],
                    url:[
                        { required: true, max:100, message: '限制字符长度' },
                    ],
                    sort:[
                        { required: true, type: 'integer', message: '序号应为非负整数' },
                        { type: 'integer', min: 0, max: 20, message: '序号最大值为20' }
                    ],
                    icon:[
                        { required: false, max:100, message: '限制字符长度' },
                    ],
                    viewDesc:[
                        { required: false, max:100, message: '长度不能超过 100 个字符' },
                    ]
                },
                selectView:{
                    viewId:'',
                    viewName:''
                },
                searchForm:{
                    type:'1',//初始默认 搜索后台功能
                },
                form:{},
                viewList:[],
                viewTreeList:[],
                defaultProps: {
                    children: 'children',
                    label: 'viewName'
                },
                loading:true
            }
        },
        components: {
        },
        created(){
            
        },
        mounted() {
            this.searchForm.type = 1;//初始默认 搜索后台功能
            this.getList();
        },
        methods:{
            handleNodeClick(data) {
                var {viewId,viewName} = data;
                this.selectView = {viewId,viewName};
                this.getSubList();
                console.log(1)
            },
            getList(isChangeSearch){//树形结构
                if(isChangeSearch){
                    this.tableData = [];
                }
                return new Promise((resolve,reject)=>{
                    this.loading=true;
                    axios.get(`view/getTree?type=${this.searchForm.type}`,{
                    })
                    .then( (res)=> {
                        this.viewList = res.data;
                        this.viewTreeList = [{
                            viewName: (this.searchForm.type?'后台功能':'前台功能'),
                            viewId: '',
                            type: this.searchForm.type,
                            children: toTree(res.data)
                        }];
                        this.loading=false;
                        resolve();
                    })
                    .catch( (error)=> {
                        this.viewTreeList = [];
                        this.$notify.error({title: '错误',message:error||'获取表格列表失败！'});
                    });
                });
                function toTree(data) {
                    var parentIdData = [];
                    data.forEach(function (item) {
                        parentIdData.push(item.parentId||'');
                        if(item.hasOwnProperty('children')){
                            delete item.children;
                        }
                    });
                    var val = [];
                    data.forEach(function (item,index) {
                        var parent = data.find(t=>t.viewId==item.parentId);
                        if (parent) {
                            (parent.children || ( parent.children = [] )).push(item);
                            if(typeof parent.lastIndex!=='number'){
                                parent.lastIndex = parentIdData.lastIndexOf(item.parentId);
                            }
                            if(index==parent.lastIndex){
                                parent.children = parent.children.sort((a,b)=>a.sort-b.sort);
                            }
                        } else {
                            val[item.sort] = item;
                        }
                    });
                    val = val.filter(t=>!!t);
                    return val;
                }
            },
            getSubList:function(){//获取右侧子功能table
                if(this.selectView.viewId){//获取子集功能
                    var selectedItem = this.viewList.find(t=>t.viewId==this.selectView.viewId);
                    var selectedItemChild = this.viewList.filter(t=>t.parentId==this.selectView.viewId).sort((a,b)=>a.sort-b.sort);
                    console.log(selectedItem,selectedItemChild)
                    if(!selectedItem){
                        this.tableData = [];
                        return;
                    }
                    this.tableData = [selectedItem,...selectedItemChild].map(({children,...arr})=>({...arr}))
                }else{//获取最顶级功能
                    this.tableData = this.viewList.filter(t=>(!t.parentId||t.parentId=='0')).map(({children,...arr})=>({...arr})).sort((a,b)=>a.sort-b.sort);
                }
            },
            async del(id){
                try{
                    await this.$confirm('确定需要删除该功能?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                    await axios.delete(`view/remove?viewId=${id}`);
                    await this.getList();
                    this.getSubList();
                    this.$notify({title: '成功',message: '删除成功！',type: 'success'});
                }catch(error){
                    if(error=='cancel'||error=='close'){
                        return;
                    }
                    this.$notify.error({ title: '错误',message: error || '删除失败！' });
                }
            },
            add (data) {
                console.log(data)
                this.dialogFormVisible = true
                this.form = {
                    valid: true, // 默认有效
                    parentId: data.viewId,
                    type: data.type
                };
                this.$nextTick(() => {
                    this.$refs.form.clearValidate()
                });
            },
            edit (id) {
                this.dialogFormVisible = true;
                axios.get(`view/get?viewId=${id}`).then((res)=>{
                    var {lastModifiedTime,creationTime,isLeaf,...arr} = res.data;
                    // arr.is_leaf = isLeaf;
                    arr.parentId = arr.parentId||'';
                    this.form = arr;
                }).catch( (error)=> {
                });
            },
            async save(){     
                var errorInfo=this.validateFun();
                if(errorInfo){
                    this.$notify({title: '警告',message: errorInfo,type: 'warning',duration:1200});
                    return;
                }
                try{
                    await axios[this.form.viewId?'put':'post'](`view/${this.form.viewId?'update':'add'}`,this.form,{});
                    await this.getList();
                    this.getSubList();
                    this.dialogFormVisible = false;
                }catch(error){
                    this.$notify.error({title: '错误',message :error ||'保存失败！'});
                }
            },
            validateFun:function(){
                var errorInfo=[]; 
                this.$refs.form.validateField(['viewName', 'valid', 'url', 'sort', 'icon', 'viewDesc'],(re)=>{
                    if(re){
                        errorInfo.push(re);
                    }
                });
                return errorInfo.join(',');
            }
        }
    }
</script>
<style scoped>
    .view{
        display: flex;
        justify-content: space-between;
    }
    .view-left{
        width: 30%;
        padding-right: 5px;
        border: 1px solid #ebeef5;
        padding: 5px;
        margin-right: 5px;
        height: fit-content;
    }
    .view-right{
        width: 70%;
    }
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
    .custom-tree-node i{
        font-size: 16px;
        color: #C0C4CC;
    }
</style>